// auth: macro gu
// email&skype: macrogu@hotmail.com

#pragma once

#include <mysql.h>
#include <string>
#include <sstream>
#include <queue>
#include <mutex>
#include <thread>

#include "log.h"
#include "read_conf.h"
#include "singleton.h"


// use single-mode 

struct stStoreMachineData
{
	std::string clientKey;
	unsigned int memoryLimit;   // percentage
	unsigned int cpuLimit;      // percentage
	unsigned int processesLimit;
};

class CDbOperator : public ISingleton<CDbOperator>
{
	public:

		// push need store data to DB queue
		void PushBackToDbQueue(const stStoreMachineData& needStoreData);

	protected:
		//insert data to DB
		bool InserDataToDB(const std::string& clientKey, const unsigned int& memory,
				const unsigned int& cpu, const unsigned int& processes);

		//connect to database
		bool Connect();
		void DisConnect();

		void threadStoreDatabase();

	private:
		MYSQL* m_mysql;
		bool m_bConnectDb;
		stMysqlInfo m_MysqlInfo;

		std::thread* StoreMachineData;

		std::queue<stStoreMachineData> qAllNeedStoreData;
		std::mutex databaseMutex;

		friend ISingleton<CDbOperator>;
		friend class std::auto_ptr<CDbOperator>;
		CDbOperator();

		~CDbOperator();
};

